#pragma once
#include "log.hpp"
#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>


class tcpClient{
public:
    tcpClient(const std::string& serverip,const int16_t& serverport) :_serverip(serverip),_serverport(serverport),_sockfd(-1)
    {}
    
    void initClient(){
        _sockfd = socket(AF_INET,SOCK_STREAM,0);
        if(_sockfd == -1){
            logmessage(FATAL,"socket filed!");
            exit(1);
        }else logmessage(NORMAL,"socket success");
    }

    void start(){
        sockaddr_in remote;
        socklen_t len = sizeof remote;
        memset(&remote,0,len);
        remote.sin_family = AF_INET;
        remote.sin_addr.s_addr = inet_addr(_serverip.c_str());
        remote.sin_port = htons(_serverport);
        if(connect(_sockfd,(sockaddr*)&remote,len) != 0){
            logmessage(FATAL,"connect filed!");
            exit(1);
        }
        logmessage(NORMAL,"connect succuss!");
        while(true){
            std::string message;
            std::getline(std::cin,message);
            ssize_t r = write(_sockfd,message.c_str(),message.size());
            if(r == -1){
                logmessage(ERROR,"write filed");
            }else{
                //std::cout<<"fa shong cg"<<std::endl;
            }
        #define MAXBUFFER 1024
            char buffer[MAXBUFFER];
            ssize_t s = read(_sockfd,buffer,MAXBUFFER);
            if(s >0){
                buffer[s] = 0;
                std::cout<<buffer<<std::endl;
            }else if(s == 0){
                logmessage(ERROR,"read filed,server close");
                break;
            }
        }
    }


    ~tcpClient(){
        close(_sockfd);
    }

private:
    std::string _serverip;
    uint16_t _serverport;
    int _sockfd;
};